package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"useryk/model/mysql"
	"useryk/model/redisinit"

	"useryk/userrpc/internal/svc"
	"useryk/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *userrpc.ProductListRequest) (*userrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	var product []mysql.Product
	page := in.Page
	if page <= 0 {
		page = 1
	}
	size := in.Size
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size
	key := "list" + strconv.FormatInt(page, 10) + in.Name + strconv.FormatInt(size, 10)
	get := redisinit.Rdb.Get(key)
	if get.Val() == "" {
		query := mysql.DB.Model(&mysql.Product{})
		if in.Name != "" {
			query = query.Where("name = ?", in.Name)
		}
		query.Offset(int(offset)).Limit(int(size)).Order("productprice desc").Find(&product)
		marshal, _ := json.Marshal(&product)
		redisinit.Rdb.Set(key, marshal, time.Hour*24)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
		fmt.Println("redis")
	}
	var lists []*userrpc.ProductList
	for _, m := range product {
		list := userrpc.ProductList{
			Productid:    int64(m.ID),
			Categorieid:  m.Categorieid,
			Num:          m.Num,
			Name:         m.Name,
			Categorienum: m.Categorienum,
			Productprice: m.Productprice,
			Costprice:    m.Costprice,
			Image:        m.Image,
		}
		lists = append(lists, &list)
	}
	return &userrpc.ProductListResponse{
		List: lists,
	}, nil
}
